package test.android;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.widget.TextView;

public class androidtest extends Activity implements SensorEventListener {
	/** Called when the activity is first created. */
	private TextView myTextView;
	SoundPool myPlayer;
	private Shaker myShaker;
	static final int SHAKE_THRESHOLD = 2;
	static final int SHAKE_GAP = 50;
	private VolumeController vc;
	private ModeController mc;
	private int[] soundMap;
	float volume = 0;
	int mode = 0;
	
	private void initSoundResource(){
		soundMap = new int[3]; //3 types of sound
		soundMap[0] = myPlayer.load(this, R.raw.song1, 1);
		soundMap[1] = myPlayer.load(this, R.raw.song2, 1);
		soundMap[2] = myPlayer.load(this, R.raw.song3, 1);
	}
	
	private void playMusic(float v, int m) {
		myPlayer.play(soundMap[m], 1, 1, 1, 0, 1f);
	}	
	private void destroyMusic(int m) {
		myPlayer.stop(soundMap[m]);
	}
		
	private class ShakeHandler implements Shaker.Callback {
		public void shakingStarted(SensorEvent e, float v) {
			volume = v;
			mode = mc.getMode(e.values[0], e.values[1], e.values[2]);
			System.out.println("volume "+volume);
			System.out.println("mode "+mode);
			playMusic(volume, mode);
			myTextView = (TextView) findViewById(R.id.myTextView);
			String welcome_mes = "Shaking!!!!!!!!!!!";
			myTextView.setText(welcome_mes);
		}
		public void shakingStopped() {
			destroyMusic(mode);
			myTextView = (TextView) findViewById(R.id.myTextView);
			String welcome_mes = "Quiet..........";
			myTextView.setText(welcome_mes);
		}
	};

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		vc = new VolumeController();
		mc = new ModeController();
		myPlayer = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
		initSoundResource();
		myShaker = new Shaker(this, SHAKE_THRESHOLD, SHAKE_GAP,
				new ShakeHandler(), vc, mc);
	}

	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		myShaker.listener.onAccuracyChanged(arg0, arg1);
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		myShaker.listener.onSensorChanged(event);
	}
	
}
